<template>
  <div v-if="show" class="component-autoupdate animate__animated animate__fast animate__bounceInUp">
    <el-button  type="success" class="btn" size="small" @click="onReboot">{{ lang.t('components.appupdate.btn') }}</el-button>
    <div class="version">
      {{ lang.t('components.appupdate.title', { version }) }}
    </div>
    <div class="content">{{ versionContent }}</div>
  </div>
</template>
<script>
import { ref } from 'vue'
import app from '@/app'
import { version as getVersion } from '@/api/manage'
import http from '@/api/http'
import compressing from 'compressing'
import path from 'path'
import fs from 'fs'

export default {
  setup() {
    // 显示
    const show = ref(false)
    const showOut = ref(false)
    // 版本号
    const version = ref('')
    // 版本内容
    const versionContent = ref('')

    // 显示
    const onShow = () => {
      showOut.value = false
      show.value = true
    }

    // 重启
    const onReboot = () => {
      app.window.reboot()
    }

    const start = () => {
      if(process.env.NODE_ENV == 'development') return

      // 增量更新
      http.get(process.env.VUE_APP_UPDATE_URL + '/latest.json?' + Date.now()).then(res => {
        // 开始更新
        updateApp(res.url, res.version)
      })
    }

    // 版本号对比
    const hasUpdate = (ver) => {
      const appVersion = app.window.version().split('.')
      const newVersion = ver.split('.')
      for (let index = 0; index < newVersion.length; index++) {
        if(Number(newVersion[index]) > Number(appVersion[index])) {
          return true
        }
      }
    }

    // 增量更新
    const updateApp = (url, ver) => {
      // 判断是否需要更新
      if(!hasUpdate(ver)) return
      // 新的版本号
      version.value = ver
      // 加载更新内容
      getVersion().then(res => {
        versionContent.value = res.data[0].content
      })
      
      // 下载更新包
      http.request({
        url,
        responseType: 'arraybuffer',
      }).then(res => {
        // APP目录
        const appPath = path.join(app.window.appPath(), 'resources', 'app')
        // 备份app目录 -> 当前版本号目录
        fs.renameSync(
          appPath, 
          path.join(app.window.appPath(), 'resources', app.window.version())
        )
        // 解压到app目录
        compressing.zip.uncompress(Buffer.from(res), appPath)

        // 提示
        onShow()
      })
    }

    return {
      lang: app.lang,
      show,
      showOut,
      version,
      versionContent,
      onShow,
      onReboot,
      start
    }
  }
}
</script>